package com.lukk.util.jpush;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NativeHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

public class JPushUtil {
	private static Logger LOG = LogManager.getLogger(JPushUtil.class.getName());
	// test mwechant account
	protected static final String APP_KEY_MERCHANT = "02bcdd4b139123cb87210bcd";
	protected static final String MASTER_SECRET_MERCHANT = "532ec820499b7e3a7ff32903";

	// test worker account
	protected static final String APP_KEY_WORKER = "0268ea18edb27cf7ce272a14";
	protected static final String MASTER_SECRET_WORKER = "3f689c30cc72b37424d84c50";

	// official merchant account
	protected static final String APP_KEY_MERCHANT_OFFICIAL = "a34fb7ab904c8615fc359202";
	protected static final String MASTER_SECRET_MERCHANT_OFFICIAL = "4b332fb9252c503b0aec5aa5";

	// official worker account
	protected static final String APP_KEY_WORKER_OFFICIAL = "3e77ad1648b09e2ec3cc0c01";
	protected static final String MASTER_SECRET_WORKER_OFFICIAL = "9acdbbf17b76fa4dc5c74336";

	public static PushPayload buildPushObject_all(String alert, String msgContent, Map<String, String> extras,
			String alias) {
		Notification notification = Notification.newBuilder()
				.addPlatformNotification(IosNotification.newBuilder().incrBadge(1).setAlert(alert).setSound("default")
						.setContentAvailable(true).addExtra("from", "JPush").addExtras(extras).build())
				.build();
		return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.alias(alias))
				.setNotification(notification)
				.setMessage(Message.newBuilder().setMsgContent(msgContent).addExtras(extras).build())
				.setOptions((Options.newBuilder().setApnsProduction(true).setTimeToLive(0).build())).build();
	}

	/**
	 * 根据一个alias推送信息
	 * 
	 * @param alert
	 * @param msgContent
	 * @param extras
	 * @param alias
	 */
	public static void pushDialogByOneAlias(String alert, String msgContent, Map<String, String> extras, String alias) {
		ClientConfig clientConfig = ClientConfig.getInstance();
		final JPushClient jpushClient = new JPushClient(MASTER_SECRET_MERCHANT_OFFICIAL, APP_KEY_MERCHANT_OFFICIAL, null, clientConfig);
		String authCode = ServiceHelper.getBasicAuthorization(APP_KEY_MERCHANT_OFFICIAL, MASTER_SECRET_MERCHANT_OFFICIAL);
		NativeHttpClient httpClient = new NativeHttpClient(authCode, null, clientConfig);
		jpushClient.getPushClient().setHttpClient(httpClient);
		PushPayload payload = buildPushObject_all(alert, msgContent, extras, alias);
		try {
			PushResult result = jpushClient.sendPush(payload);
			LOG.info("Got result - " + result);

		} catch (APIConnectionException e) {
			LOG.error("Connection error. Should retry later. ", e);
			LOG.error("Sendno: " + payload.getSendno());

		} catch (APIRequestException e) {
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			LOG.info("Msg ID: " + e.getMsgId());
			LOG.error("Sendno: " + payload.getSendno());
		}
	}

	public static void start(String ALERT, String MSG_CONTENT, Integer type, Map<String, String> extras, String city) {
		JPushClient jpushClient = null;
		if (type == 0) {// 新订单
			jpushClient = new JPushClient(MASTER_SECRET_WORKER_OFFICIAL, APP_KEY_WORKER_OFFICIAL, null, ClientConfig.getInstance());
		}
		// For push, all you need do is to build PushPayload object.
		PushPayload payload = buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(ALERT, MSG_CONTENT, extras, city);

		try {
			PushResult result = jpushClient.sendPush(payload);
			LOG.info("Got result - " + result);

		} catch (APIConnectionException e) {
			// Connection error, should retry later
			LOG.error("Connection error, should retry later", e);

		} catch (APIRequestException e) {
			// Should review the error, and fix the request
			LOG.error("Should review the error, and fix the request", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
		}
	}

	public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(String ALERT, String MSG_CONTENT,
			Map<String, String> extras, String city) {
		return PushPayload.newBuilder().setPlatform(Platform.android_ios()).setAudience(Audience.tag(city))
				.setNotification(Notification.newBuilder()
						.addPlatformNotification(IosNotification.newBuilder().setAlert(ALERT).setBadge(1).autoBadge()
								.setSound("default").setContentAvailable(true).addExtra("from", "JPush").build())
						.build())
				.setMessage(Message.newBuilder().setMsgContent(MSG_CONTENT).addExtras(extras).build())
				.setOptions(Options.newBuilder().setApnsProduction(true).setTimeToLive(0).build()).build();
	}

	// 推送新订单或者加价悬赏
	public static void JpushIndent(Map<String, Object> map) {
		Map<String, String> send = new HashMap<>();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		try {
			date = simpleDateFormat.parse(map.get("subscribeTime").toString());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		long timeStemp = date.getTime();
		send.put("subscribeTime", String.valueOf(timeStemp));
		// 进行推送 0推送订单 1推送消息
		send.put("msgType", "0");
		send.put("status", map.get("status").toString());
		send.put("city", map.get("province").toString() + map.get("city").toString() + map.get("area").toString());
		send.put("name", map.get("name").toString());
		send.put("indentId", map.get("indentId").toString());
		send.put("cuAdId", map.get("cuAdId").toString());
		send.put("addPrice", map.get("addPrice").toString());
		send.put("phone", map.get("phone").toString());
		if (map.get("motorNum") != null) {
			send.put("motorNum", map.get("motorNum").toString());
		}
		if (map.get("bigouNum") != null) {
			send.put("bigouNum", map.get("bigouNum").toString());
		}
		if (map.get("sizhuagouNum") != null) {
			send.put("sizhuagouNum", map.get("sizhuagouNum").toString());
		}
		send.put("beginTime", map.get("beginTime").toString());
		send.put("address", map.get("address").toString());
		send.put("type", map.get("type").toString());

		if (map.get("baseAddress") != null && "无".equals((String) map.get("baseAddress"))) {
			send.put("baseAddress", (String) map.get("baseAddress"));
			send.put("detailAddress", (String) map.get("detailAddress"));
			send.put("isNeedTakeGoods", "1");
		} else {
			send.put("isNeedTakeGoods", "0");
		}

		if (map.get("weiXbody") != null) {
			send.put("weiXbody", map.get("weiXbody").toString());
		}
		send.put("merchantsPrice", map.get("merchantsPrice").toString());
		if (map.get("roomNumB") != null) {
			send.put("roomNumB", map.get("roomNumB").toString());
		}

		if (map.get("remark") != null) {
			send.put("remark", map.get("remark").toString());
		}
		send.put("indentPrice", map.get("indentPrice").toString());
		// 这里的number是有多少个商品
		if (map.get("number") != null) {
			send.put("number", map.get("number").toString());
		}
		if ((Integer) map.get("type") == 0) {// 这是测量订单
			// 判断一下是否加价
			if ((Double) map.get("addPrice") != 0.0) {// 加价了
				JPushUtil.start("测量订单￥" + map.get("indentPrice") + "加价￥" + map.get("addPrice"),
						"测量订单￥" + map.get("indentPrice") + "加价￥" + map.get("addPrice"), 0, send,
						(String) map.get("areaCode"));// 按区域码发送推送
			} else {// 未加价
				JPushUtil.start("测量订单￥" + map.get("indentPrice"), "测量订单￥" + map.get("indentPrice"), 0, send,
						(String) map.get("areaCode"));
			}
		} else if ((Integer) map.get("type") == 1) {// 这是安装订单
			if ((Double) map.get("addPrice") != 0.0) {// 这是加价了
				if ((Integer) map.get("motorNum") != 0) {// 含电动
					JPushUtil.start("安装订单含电动窗帘￥" + map.get("indentPrice") + "加价￥" + map.get("addPrice"),
							"安装订单含电动窗帘￥" + map.get("indentPrice") + "加价￥" + map.get("addPrice"), 0, send,
							(String) map.get("areaCode"));
				} else {// 不含电动
					JPushUtil.start("安装订单￥" + map.get("indentPrice") + "加价￥" + map.get("addPrice"),
							"安装订单￥" + map.get("indentPrice") + "加价￥" + map.get("addPrice"), 0, send,
							(String) map.get("areaCode"));
				}
			} else {// 这是没有加价
				if ((Integer) map.get("motorNum") != 0) {// 含电动
					JPushUtil.start("安装订单含电动窗帘￥" + map.get("indentPrice"), "安装订单含电动窗帘￥" + map.get("indentPrice"), 0,
							send, (String) map.get("areaCode"));
				} else {// 不含电动
					JPushUtil.start("安装订单￥" + map.get("indentPrice"), "安装订单￥" + map.get("indentPrice"), 0, send,
							(String) map.get("areaCode"));
				}
			}
		} else {// 这是维修订单
			if ((Double) map.get("addPrice") != 0.0) {// 这是加价了
				if ((Integer) map.get("motorNum") != 0) {// 含电动
					JPushUtil.start("维修订单含电动窗帘￥" + map.get("indentPrice") + "加价￥" + map.get("addPrice"),
							"维修订单含电动窗帘￥" + map.get("indentPrice") + "加价￥" + map.get("addPrice"), 0, send,
							(String) map.get("areaCode"));
				} else {
					JPushUtil.start("维修订单￥" + map.get("indentPrice") + "加价￥" + map.get("addPrice"),
							"维修订单￥" + map.get("indentPrice") + "加价￥" + map.get("addPrice"), 0, send,
							(String) map.get("areaCode"));
				}
			} else {// 这是没有加价
				if ((Integer) map.get("motorNum") != 0) {// 含电动
					JPushUtil.start("维修订单含电动窗帘￥" + map.get("indentPrice"), "维修订单含电动窗帘￥" + map.get("indentPrice"), 0,
							send, (String) map.get("areaCode"));
				} else {// 不含电动
					JPushUtil.start("维修订单￥" + map.get("indentPrice"), "维修订单￥" + map.get("indentPrice"), 0, send,
							(String) map.get("areaCode"));
				}
			}
		}

	}

	@Test
	public void test1() throws Exception {
		String alert = "补差价提醒";
		String msgContent = "你有需要补的差价，请及时处理";
		String alias = "863549038499622";
		// String alias = "d369022995a34b118f35797fcf3d3525";
		Map<String, String> extras = new HashMap<String, String>();
		extras.put("from", "JPush");
		extras.put("msgType", "3");
		extras.put("msgTitle", alert);
		for (int i = 0; i < 1000; i++) {
			Thread.sleep(1000);
			JPushUtil.pushDialogByOneAlias(alert, msgContent, extras, alias);
			// JPushUtil.pushDialogByOneAlias(alert, msgContent, extras,
			// "d369022995a34b118f35797fcf3d3525");
		}
	}

	@Test
	public void test2() throws Exception {

	}
}
